﻿using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace Drivers
{
    public class TempSensor
    {
        #region
        const byte TEMPERATURE = 0x00;
        const byte CONFIGURATION = 0x01;
        const byte PRODUCT_ID = 0x07;
        #endregion

        private const int address = 0x48;
        private const int clockRateKHz = 400;
        private I2CDevice device;

        public TempSensor()
        {
            I2CDevice.Configuration config = new I2CDevice.Configuration(address, clockRateKHz);
            device = new I2CDevice(config);
        }

        public double ReadTemperature()
        {
            ResetPointer();

            //prepare buffer to write byte 0 : register
            byte[] outBuffer = new byte[] { address, TEMPERATURE };
            I2CDevice.I2CWriteTransaction writeTransaction = I2CDevice.CreateWriteTransaction(outBuffer);

            //prepare buffer to read 2 bytes
            byte[] tempRead = new byte[2];
            I2CDevice.I2CReadTransaction readTransaction = I2CDevice.CreateReadTransaction(tempRead);

            //execute both transactions
            I2CDevice.I2CTransaction[] transactions = new I2CDevice.I2CTransaction[] { writeTransaction, readTransaction };


            int transferred;
            double convertTempRead;
            if ((transferred = device.Execute(transactions, 100)) == 0)
            {
                Debug.Print("Error connection");
                convertTempRead = 0;
            }
            else
            {
                if (tempRead[1] == 128)
                    convertTempRead = tempRead[0] + 0.5;
                else
                    convertTempRead = tempRead[0];
            }

            return convertTempRead;
        }

        private void ResetPointer()
        {
            byte[] register = new byte[] { address, TEMPERATURE };
            byte[] tempRead = new byte[2];
            I2CDevice.I2CTransaction[] transaction = new I2CDevice.I2CTransaction[2];
            transaction[0] = I2CDevice.CreateWriteTransaction(register);
            transaction[1] = I2CDevice.CreateReadTransaction(tempRead);
        }
    }
}
